<template>
    <div id="VJFile">
        <el-upload
                :action="action"
                :show-file-list="false"
                :headers="headers"
                v-loading="loading"
                :before-upload="()=>loading=true"
                :on-error="onUploadError"
                :on-success="onUpload">
            <el-button size="small" type="primary">{{fileName||'点击上传'}}</el-button>
        </el-upload>
    </div>
</template>
<script lang="ts">
    import Vue, {ComponentOptions, VueConstructor} from "vue"
    import Component from 'vue-class-component'
    import emitter from 'element-ui/src/mixins/emitter';
    import {defaultProp, ModelSync} from "vijay-util";
    import {Prop, Watch} from "vue-property-decorator";
    import {Message} from "element-ui";

    @Component({
        mixins: [emitter],
    })
    export default class VJFile extends Vue implements ComponentOptions<Vue> {
        name = "VJFile"
        loading = false;
        fileName = ""
        @ModelSync(defaultProp("")) fakeValue!: any;
        get combineConfig() {
            return this.combineWith<VFile.configType>(VFile.config);
        }
        get action() {
            return Vue.$uploadPath
        }
        get headers() {
            const header = {};
            const Authorization = localStorage.getItem("Authorization");
            const gameId = localStorage.getItem("gameId");
            Authorization && (header["Admin-Authorization"] = Authorization);
            gameId && (header["gameId"] = gameId);
            return header
        }
        onUploadError() {
            this.loading = false
            return Message.error("上传失败！")
        }
        onUpload(res,{name}) {
            if (!res?.data) return this.onUploadError();
            this.fileName = name;
            this.fakeValue = res.data;
            this.loading = false;
            this.$emit("uploaded")
        }
        @Watch("fakeValue")
        valueChange() {
            this.dispatch('ElFormItem', 'el.form.blur', [this.fakeValue]);
        }
    }
</script>

<style scoped lang="scss">
    @import "~assets/common.scss";
    #VJFile {
    }
</style>
